package com.baijiayun.live.ui.toolbox.questionanswer

import android.annotation.SuppressLint
import androidx.lifecycle.MutableLiveData
import com.baijiayun.live.ui.base.BaseViewModel
import com.baijiayun.live.ui.base.RouterViewModel
import com.baijiayun.live.ui.isAdmin
import com.baijiayun.livecore.context.LPConstants
import com.baijiayun.livecore.context.LPError
import com.baijiayun.livecore.models.*
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by yongjiaming on 2019-10-30
 * Describe:fragment层vm绑定各自数据
 */
class QAViewModel(val routerViewModel: RouterViewModel) : BaseViewModel() {
    //问答部分
    val questionList = MutableLiveData<List<LPQuestionPullResItem>>()
    val notifyLoadEmpty = MutableLiveData<Unit>()
    var needScroll = false
    var showNewReminder = false

    //老师 待回复 8  待发布 4，6 已发布1
    //老师待回复 &8!=0 ,待发布只取6,4(不确定有没有加上不影响结果) 已发布 &1!=1
    //学生我的问题15（isSelf= true,默认false）已发布1
    var tabStatus = QADetailFragment.QATabStatus.AllStatus
    private val allQuestions = ArrayList<LPQuestionPullResItem>()
    private var status = QuestionStatus.QuestionPublished.status
    private var isSelf = false
    private var maxPage = -1
    private var page = 0

    /**
     * 老师total正常取值，学生取pull_res,send_res,因为是发布广播服务端不能处理不能取pub,
     * 又因为学生是取15，所以这里pub时total不用变化
     */
    private var total = 0
    private val PAGE_COUNT = LPConstants.DEFAULT_COUNT_PER_PAGE

    private val liveRoom by lazy {
        routerViewModel.liveRoom
    }

    @SuppressLint("CheckResult")
    override fun subscribe() {
        compositeDisposable.add(liveRoom.toolBoxVM.observableOfQuestionPullRes
                .observeOn(AndroidSchedulers.mainThread())
                .filter {
                    val b = if (isAdmin(liveRoom)) {
                        //待发布只有6和4
                        if (it.status != 6 && it.status != 4 && tabStatus == QADetailFragment.QATabStatus.ToPublish) {
                            false
                        } else {
                            it.status and status != 0
                        }
                    } else {
                        //异或取反=同或 学生我的isSelf是true 接收也是true才走进来
                        !(isSelf xor it.isSelf)
                    }
                    b
                }
                .filter {
                    val isNotEmpty = it.list?.isNotEmpty() == true
                    if (!isNotEmpty) {
                        if (page >= 0) {
                            page--
                        }
                        notifyLoadEmpty.value = Unit
                    }
                    isNotEmpty
                }
                .map {
                    //老师待发布只取6和4
                    if (tabStatus == QADetailFragment.QATabStatus.ToPublish) {
                        val list = ArrayList<LPQuestionPullResItem>()
                        for (item in it.list) {
                            if (item.status == 6 || item.status == 4) {
                                list.add(item)
                            }
                        }
                        it.list = list
                    }
                    it
                }
                .subscribe {
                    if (maxPage == -1) {
                        total = getTotal(it.lpQuestionCategoryModel)
                        maxPage = getPageCeil(total)
                        if (maxPage > 1) {
                            //首次加载请求最新的一页
                            page = maxPage - 1
                            loadMoreQuestions(status, isSelf)
                            return@subscribe
                        }
                        allQuestions.addAll(it.list)
                        allQuestions.sortWith(Comparator { o1, o2 -> (o1.lastTime - o2.lastTime).toInt() })
                        val hasLoadedPage = getPageCeil(allQuestions.size)
                        page = maxPage - 1 - hasLoadedPage
                        needScroll = false
                        showNewReminder = false
                        questionList.value = allQuestions

                    } else {
                        allQuestions.addAll(it.list)
                        allQuestions.sortWith(Comparator { o1, o2 -> (o1.lastTime - o2.lastTime).toInt() })
                        total = getTotal(it.lpQuestionCategoryModel)
                        maxPage = getPageCeil(total)
                        val hasLoadedPage = getPageCeil(allQuestions.size)
                        page = maxPage - 1 - hasLoadedPage
                        needScroll = false
                        showNewReminder = false
                        questionList.value = allQuestions
                    }
                })
        //不dispose掉，因为liveRoomViewModle里面需要订阅
        liveRoom.toolBoxVM.observableOfQuestionPub
                .filter { !compositeDisposable.isDisposed }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    var removedItem: LPQuestionPullResItem? = null
                    for (lpQuestionPullResItem1 in allQuestions) {
                        if (it.id == lpQuestionPullResItem1.id) {
                            removedItem = lpQuestionPullResItem1
                            allQuestions.remove(lpQuestionPullResItem1)
                            break
                        }
                    }
                    val lpQuestionPullResItem = LPQuestionPullResItem()
                    lpQuestionPullResItem.lastTime = it.lastTime
                    lpQuestionPullResItem.id = it.id
                    lpQuestionPullResItem.status = it.status
                    if (it.content?.isNotEmpty() == true) {
                        lpQuestionPullResItem.itemList = it.content
                    } else {
                        lpQuestionPullResItem.itemList = removedItem?.itemList ?: ArrayList()
                    }
                    if (isAdmin(liveRoom)) {
                        if (it.status and status != 0) {
                            if (it.status == 6 || it.status == 4 || tabStatus != QADetailFragment.QATabStatus.ToPublish) {
                                allQuestions.add(lpQuestionPullResItem)
                            }
                        }
                    } else {
                        //过滤学生的状态
                        if (isSelf) {
                            if (it.owner == routerViewModel.liveRoom.currentUser.number && it.status and status != 0) {
                                allQuestions.add(lpQuestionPullResItem)
                                showNewReminder = true
                            }
                        } else {
                            if (it.status and status != 0) {
                                allQuestions.add(lpQuestionPullResItem)
                                showNewReminder = true
                            }
                        }
                    }
                    allQuestions.sortWith(Comparator { o1, o2 -> (o1.lastTime - o2.lastTime).toInt() })
                    if (!isSelf) total = getTotal(it.categoryModel)
                    maxPage = getPageCeil(total)
                    val hasLoadedPage = getPageCeil(allQuestions.size)
                    page = maxPage - 1 - hasLoadedPage
                    needScroll = false
                    questionList.value = allQuestions
                }
        liveRoom.toolBoxVM.observableOfQuestionSendRes
                .filter { !compositeDisposable.isDisposed }
                .filter {
                    val b = if (isAdmin(liveRoom)) {
                        //待发布取6和4
                        if (it.status != 6 && it.status != 4 && tabStatus == QADetailFragment.QATabStatus.ToPublish) {
                            false
                        } else {
                            it.status and status != 0
                        }
                    } else {
                        if (isSelf) {
                            it.from.number == routerViewModel.liveRoom.currentUser.number && it.status and status != 0
                        } else {
                            it.status and status != 0
                        }
                    }
                    b
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    val lpQuestionPullResItem = LPQuestionPullResItem()
                    lpQuestionPullResItem.id = it.id
                    lpQuestionPullResItem.lastTime = it.lastTime
                    lpQuestionPullResItem.status = it.status
                    val lpQuestionPullListItem = LPQuestionPullListItem()
                    lpQuestionPullListItem.content = it.content
                    lpQuestionPullListItem.from = it.from
                    lpQuestionPullListItem.time = it.time
                    val list: MutableList<LPQuestionPullListItem> = java.util.ArrayList()
                    list.add(lpQuestionPullListItem)
                    lpQuestionPullResItem.itemList = list
                    allQuestions.add(lpQuestionPullResItem)
                    allQuestions.sortWith(Comparator { o1, o2 -> o1.lastTime.toInt() - o2.lastTime.toInt() })
                    total = getTotal(it.lpQuestionCategoryModel)
                    maxPage = getPageCeil(total)
                    val hasLoadedPage = getPageCeil(allQuestions.size)
                    page = maxPage - 1 - hasLoadedPage
                    //仅学生自己提问滑动底部
                    needScroll = !isAdmin(liveRoom) && tabStatus == QADetailFragment.QATabStatus.AllStatus
                    showNewReminder = false
                    questionList.value = allQuestions
                }
    }

    /**
     *
     * 状态对应的tab
     */
    private fun getTotal(model: LPQuestionCategoryModel): Int {
        return when (tabStatus) {
            QADetailFragment.QATabStatus.Published -> model.pub
            QADetailFragment.QATabStatus.ToAnswer -> model.total - model.reply
            QADetailFragment.QATabStatus.ToPublish -> model.replynopub
            else -> model.total
        }
    }

    private fun getPageCeil(total: Int): Int {
        return if (total % PAGE_COUNT != 0) {
            total / PAGE_COUNT + 1
        } else total / PAGE_COUNT
    }

    /**
     * 加载更多数据，实际是先加载10 再9 8，下拉刷新顺序10-9-8-7-6这样子
     */
    fun loadMoreQuestions(status: Int = 15, isSelf: Boolean = false): LPError? {
        if (page >= maxPage && maxPage != -1) {
            return LPError(LPError.CODE_ERROR_INVALID_ARGUMENT)
        }
        if (page < 0) {
            return LPError(LPError.CODE_ERROR_INVALID_ARGUMENT)
        }
        val lpQuestionPullReqModel = LPQuestionPullReqModel()
        this.status = status
        this.isSelf = isSelf
        lpQuestionPullReqModel.page = page
        lpQuestionPullReqModel.countPerPage = PAGE_COUNT
        lpQuestionPullReqModel.status = status // 已发布 1,未发布 2, 已回复 4,未回复 8,全部 15}
        //0是全部，1是自己 其余数不带isSelf字段（老版本学生返回5个自己的数据和全部已发布）
        lpQuestionPullReqModel.isSelf = if(isSelf)1 else 0
        return liveRoom.toolBoxVM.requestQuestionPullReq(lpQuestionPullReqModel)
    }

    //每次切换tab刷新数据
    fun refreshQuestions() {
        page = 0
        maxPage = -1
        allQuestions.clear()
        loadMoreQuestions(status, isSelf)
    }

    /**
     * 发布问题
     */
    fun publishQuestion(questionId: String, content: String) {
        val triggerModel = LPQuestionPubTriggerModel(questionId, QuestionStatus.QuestionReplied.status or QuestionStatus.QuestionUnReplied.status or QuestionStatus.QuestionPublished.status,
                content, liveRoom.currentUser)
        liveRoom.toolBoxVM.requestQuestionPub(triggerModel)
    }

    //回复问题
    fun publishAnswer(questionId: String, content: String) {
        val triggerModel = LPQuestionPubTriggerModel(questionId, QuestionStatus.QuestionReplied.status or QuestionStatus.QuestionPublished.status, content, liveRoom.currentUser)
        liveRoom.toolBoxVM.requestQuestionPub(triggerModel)
    }

    //取消发布
    fun unPublishQuestion(questionId: String, content: String = "") {
        val triggerModel = LPQuestionPubTriggerModel(questionId, QuestionStatus.QuestionReplied.status or QuestionStatus.QuestionUnReplied.status or QuestionStatus.QuestionUnPublished.status, liveRoom.currentUser)
        if (content.isNotBlank()) {
            triggerModel.content = content
        }
        liveRoom.toolBoxVM.requestQuestionPub(triggerModel)
    }

    //生成问题
    fun generateQuestion(content: String): LPError? {
        return liveRoom.toolBoxVM.requestQuestionSend(content)
    }

    /**
     * 回复
     */
    fun saveQuestion(questionId: String, content: String) {
        val item = getReplyItem(questionId, content, allQuestions)
        var operate = QuestionStatus.QuestionReplied.status or QuestionStatus.QuestionUnPublished.status
        item?.run {
            operate = if (this.status and QuestionStatus.QuestionPublished.status != 0) {
                QuestionStatus.QuestionPublished.status or QuestionStatus.QuestionReplied.status
            } else {
                QuestionStatus.QuestionUnPublished.status or QuestionStatus.QuestionReplied.status
            }
        }
        val triggerModel = LPQuestionPubTriggerModel(questionId, operate, content, liveRoom.currentUser)
        liveRoom.toolBoxVM.requestQuestionPub(triggerModel)
    }

    private fun getReplyItem(questionId: String, content: String, list: ArrayList<LPQuestionPullResItem>): LPQuestionPullResItem? {
        for (item in list) {
            if (item.id == questionId) {
                val replayItem = LPQuestionPullListItem()
                replayItem.from = liveRoom.currentUser as LPUserModel
                replayItem.content = content
                item.itemList.add(replayItem)
                return item
            }
        }
        return null
    }
}